﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
//using Microsoft.Office.Interop.Word;

public partial class Pages_SearchMaster : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Int32 roleId = 0;
        if (!Page.IsPostBack)
        {
            roleId = Convert.ToInt32(Session["RoleId"]);
            string pageType = "";
            if (Request.QueryString != null && Request.QueryString.Count > 0)
            {
                pageType = Request.QueryString[0].ToString();
                CallDisplayUser(pageType, roleId);

            }
        }
        // grdCOmpany.Columns[3].Visible = false;

    }

    #region GridEvents

    protected void grdCOmpany_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            int roleId = 0;
            roleId = Convert.ToInt32(Session["RoleId"]);
            grdCOmpany.PageIndex = e.NewPageIndex;
            CallDisplayUser(Constants.Company.ToString(), roleId);

        }
        catch
        {
        }
    }
    protected void grdEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            int roleId = 0;
            roleId = Convert.ToInt32(Session["RoleId"]);
            grdCOmpany.PageIndex = e.NewPageIndex;
            CallDisplayUser(Constants.Employee.ToString(), roleId);
        }
        catch
        {
        }
    }
    protected void grdVehicle_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            int roleId = 0;
            roleId = Convert.ToInt32(Session["RoleId"]);
            grdVehicle.PageIndex = e.NewPageIndex;
            CallDisplayUser(Constants.Truck.ToString(), roleId);
        }
        catch
        {
        }
    }
    protected void grdMaterial_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            int roleId = 0;
            roleId = Convert.ToInt32(Session["RoleId"]);
            grdMaterial.PageIndex = e.NewPageIndex;
            CallDisplayUser(Constants.Material.ToString(), roleId);
        }
        catch
        {
        }
    }
    protected void grdChallan_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            int roleId = 0;
            roleId = Convert.ToInt32(Session["RoleId"]);
            grdChallan.PageIndex = e.NewPageIndex;
            CallListChallan();
        }
        catch
        {
        }
    }
    protected void grdBill_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {

            //  Response.Write(grdBill.PageIndex.ToString());
            //int d = grdBill.PageCount;
            //bool[] values = new bool[grdBill.PageSize];
            //List<int> chId = new List<int>();
            //CheckBox chb;
            //for (int i = 0; i < grdBill.Rows.Count; i++)
            //{
            //    chb = (CheckBox)grdBill.Rows[i].FindControl("chkSelect");
            //    if (chb != null)
            //    {
            //        values[i] = chb.Checked;

            //    }
            //}

            //Session["page" + grdBill.PageIndex] = values;
            grdBill.PageIndex = e.NewPageIndex;
            CallListBillDetails();
        }
        catch
        {
        }
    }
    protected void grdBill_PreRender(object sender, EventArgs e)
    {
        //if (Session["page" + grdBill.PageIndex] != null)
        //{
        //    CheckBox chb;
        //    bool[] values = (bool[])Session["page" + grdBill.PageIndex];
        //    for (int i = 0; i < grdBill.Rows.Count; i++)
        //    {
        //        chb = (CheckBox)grdBill.Rows[i].FindControl("chkSelect");
        //        chb.Checked = values[i];
        //    }
        //}
    }
    protected void grdChallan_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            dvError.InnerHtml = "";
            GridView grd = new GridView();
            grd = ((GridView)(sender));
            if (e.CommandName == "DeleteMaster")
            {
                Int32 rowIndex = Convert.ToInt32(e.CommandArgument);
                int id = Convert.ToInt32(((HiddenField)grd.Rows[rowIndex].Cells[0].FindControl("hdnId")).Value);
                BusinessClass.DeleteMaster(Constants.Challan, id, 0);
                CallListChallan();
            }
        }
        catch (Exception ex)
        {
            dvError.InnerHtml = "This Challan is included in the Bill, So first delete the Bill including this company and then try again";
        }

    }

    protected void grdComp_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            GridView grd = new GridView();
            grd = ((GridView)(sender));
            if (e.CommandName == "DeleteMaster")
            {
                Int32 rowIndex = Convert.ToInt32(e.CommandArgument);
                int id = Convert.ToInt32(((HiddenField)grd.Rows[rowIndex].Cells[0].FindControl("hdnId")).Value);
                BusinessClass.DeleteMaster(Constants.Company, id, 0);
                CallBindCompanyGrid(0);
            }
        }
        catch (Exception ex)
        {
            dvError.InnerHtml = "This Company is included in the Challan, So first delete the challan including this company and then try again";
        }

    }

    protected void grdTruck_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            GridView grd = new GridView();
            grd = ((GridView)(sender));
            if (e.CommandName == "DeleteMaster")
            {
                Int32 rowIndex = Convert.ToInt32(e.CommandArgument);
                int id = Convert.ToInt32(((HiddenField)grd.Rows[rowIndex].Cells[0].FindControl("hdnId")).Value);
                BusinessClass.DeleteMaster(Constants.Truck, id, 0);
                CallBindTruckGrid(0);
            }
        }
        catch (Exception ex)
        {
            dvError.InnerHtml = ex.Message;
        }

    }

    protected void grdMaterial_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            GridView grd = new GridView();
            grd = ((GridView)(sender));
            if (e.CommandName == "DeleteMaster")
            {
                Int32 rowIndex = Convert.ToInt32(e.CommandArgument);
                int id = Convert.ToInt32(((HiddenField)grd.Rows[rowIndex].Cells[0].FindControl("hdnId")).Value);
                BusinessClass.DeleteMaster(Constants.Material, id, 0);
                CallBindMaterialGrid(0);
            }
        }
        catch (Exception ex)
        {
            dvError.InnerHtml = ex.Message;
        }

    }

    protected void grdEmployee_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            GridView grd = new GridView();
            grd = ((GridView)(sender));
            if (e.CommandName == "DeleteMaster")
            {
                Int32 rowIndex = Convert.ToInt32(e.CommandArgument);
                int id = Convert.ToInt32(((HiddenField)grd.Rows[rowIndex].Cells[0].FindControl("hdnId")).Value);
                BusinessClass.DeleteMaster(Constants.Employee, id, 0);
                CallBindEmployeeGrid(0);
            }
        }
        catch (Exception ex)
        {
            dvError.InnerHtml = ex.Message;
        }

    }
    protected void grdBill_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void grdMaterial_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    #endregion

    #region Methods
    private void CallListChallan()
    {
        DataTable dt = new DataTable();
        Challan ch = new Challan();
        int status = 0;
        Session["Challan"] = null;
        status = Convert.ToInt32(ddlStatus.SelectedValue);
        string date = Request.Form[txtDate.UniqueID].ToString();
        dt = ch.ListChallan(date, txtTransport.Text, txtChallanNo.Text, 0, status);
        if (dt.Rows.Count > 0)
        {
            Session["Challan"] = dt;
            grdChallan.DataSource = dt.DefaultView;
            grdChallan.DataBind();
        }
        else
        {
            grdChallan.DataSource = new object[] { };
            grdChallan.DataBind();
        }
    }
    public string GetCompURL(string compID, string status)
    {
        return "~/Pages/CreateMaster.aspx?Type=" + Constants.Company + "&CompId=" + compID;

    }
    public string GetTruckURL(string truckID, string status)
    {
        return "~/Pages/CreateMaster.aspx?Type=" + Constants.Truck + "&TruckId=" + truckID;

    }
    public string GetEmpURL(string empId, string status)
    {

        return "~/Pages/CreateMaster.aspx?Type=" + Constants.Employee + "&EmpId=" + empId;

    }
    public string GetChallan(string chId, string status)
    {
        return "~/Pages/CreateMaster.aspx?Type=" + Constants.Challan + "&ChId=" + chId;

    }
    public string GetMaterialURL(string mid, string status)
    {
        return "~/Pages/CreateMaster.aspx?Type=" + Constants.Material + "&Mid=" + mid;

    }
    private void CallBindEmployeeGrid(int roleId)
    {
        DataTable dt = BusinessClass.GetEmployeeDetails(roleId, 0);
        grdEmployee.DataSource = dt.DefaultView;
        grdEmployee.DataBind();
    }

    private void CallBindCompanyGrid(int roleId)
    {
        DataTable dt = new DataTable();
        dt = BusinessClass.GetCompanyDetails(roleId, 0);
        grdCOmpany.DataSource = dt.DefaultView;
        grdCOmpany.DataBind();
    }

    private void CallShowPageType(Panel pan)
    {
        pan.Visible = true;
    }

    public string ImageURL(string img_id, string type, int imgNo)
    {
        return ("GetImage.aspx?id=" + img_id + "&Type=" + type + "&ImageNo=" + imgNo);
    }

    private void CallDisplayUser(string pageType, int roleId)
    {
        switch (pageType)
        {
            case Constants.Challan:
                CallShowPageType(dvChallan);
                break;
            case Constants.Company:
                CallShowPageType(PanComp);
                CallBindCompanyGrid(roleId);
                break;
            case Constants.Employee:
                CallShowPageType(dvEmployee);
                CallBindEmployeeGrid(roleId);
                break;
            case Constants.Truck:
                CallShowPageType(dvTruck);
                CallBindTruckGrid(roleId);
                break;
            case Constants.Material:
                CallShowPageType(dvMaterial);
                CallBindMaterialGrid(roleId);
                break;
            case Constants.Bill:
                CallShowPageType(panBill);
                CallFillComboBoxes();
                break;
            case "BV":
                CallShowPageType(panBillView);
                ListTransCompany(ddlTransport, BusinessClass.CompanyType.Transport);
                //  ListBillNos();
                break;
            default:
                break;
        }
    }

    private void CallBindMaterialGrid(int roleId)
    {
        DataTable dt = BusinessClass.GetMaterialDetais(roleId, 0);
        grdMaterial.DataSource = dt;
        grdMaterial.DataBind();
    }

    private DataTable CallBindTruckGrid(int roleId)
    {
        DataTable dt = BusinessClass.GetVehicleDetails(roleId, 0);
        grdVehicle.DataSource = dt.DefaultView;
        grdVehicle.DataBind();
        return dt;
    }

    #endregion

    #region ButtonClickEvents
    protected void btnGenerateBill_Click(object sender, EventArgs e)
    {
        int rate = 0;
        if (int.TryParse(txtRate.Text.Trim(), out rate))
        {
            Session["Rate"] = rate;
        }
        CallGenerateBill();
        CallListBillDetails();
        ListBillNos(0);
    }
    protected void btnCompany_Click(object sender, EventArgs e)
    {
        Response.Redirect("CompanyMaintenance.aspx");
    }
    protected void btnProfile_Click(object sender, EventArgs e)
    {
        try
        {
            int roleId = Convert.ToInt32(Session["RoleId"]);
            int userId = Convert.ToInt32(Session["UserId"]);
            Response.Redirect("UserProfile.aspx?RoleId=" + roleId.ToString() + "&UserId=" + userId.ToString());
        }
        catch (Exception ex)
        {

        }
    }
    protected void btnVehicle_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect("VehicleMaintenance.aspx");
        }
        catch (Exception ex)
        {

        }
    }
    protected void btnChallan_Click(object sender, EventArgs e)
    {
        Response.Redirect("ChallanOrigination.aspx");
    }
    protected void btnUser_Click(object sender, EventArgs e)
    {
        Response.Redirect("CreateUser.aspx");
    }
    protected void btnEmp_Click(object sender, EventArgs e)
    {
        Response.Redirect("EmployeeMaintenance.aspx");
    }
    protected void btnNewUser_Click(object sender, EventArgs e)
    {
        Response.Redirect("ApprovalSystem.aspx?PageType=E");
    }
    protected void btnApprove_Click(object sender, EventArgs e)
    {
        Response.Redirect("ApprovalSystem.aspx?PageType=CH");
    }
    protected void btnApproveCompany_Click(object sender, EventArgs e)
    {
        Response.Redirect("ApprovalSystem.aspx?PageType=C");
    }
    protected void btnApproveVehivle_Click(object sender, EventArgs e)
    {
        Response.Redirect("ApprovalSystem.aspx?PageType=V");
    }
    protected void btnApproveMaterial_Click(object sender, EventArgs e)
    {
        Response.Redirect("ApprovalSystem.aspx?PageType=M");
    }
    protected void btnApproveBill_Click(object sender, EventArgs e)
    {
        Response.Redirect("ApprovalSystem.aspx?PageType=B");
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        CallListChallan();
    }
    protected void btnMaterial_Click(object sender, EventArgs e)
    {
        Response.Redirect("Material.aspx");
    }
    protected void btnDeleteBill_Click(object sender, EventArgs e)
    {
        try
        {
            int id = Convert.ToInt32(ddlBillNos.SelectedValue);
            BusinessClass.DeleteMaster(Constants.Bill, id, 0);
            ListBillNos(0);
        }
        catch (Exception ex)
        {

            throw;
        }
    }
    #endregion

    #region Bill Details
    private void ListTransCompany(DropDownList ddl, BusinessClass.CompanyType companyType)
    {
        try
        {
            DataTable dt = new DataTable();
            dt = DataAccessClass.GetCompany(companyType);
            ddl.DataSource = dt.DefaultView;

            ddl.DataTextField = "CompanyName";
            ddl.DataValueField = "CompanyId";
            ddl.DataBind();
            ddl.Items.Add(new ListItem("Please Select", "0", true));
            ddl.SelectedValue = "0";
        }
        catch (Exception ex)
        {
        }
    }
    protected void ddlTransport_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlTransport.SelectedValue != "0")
        {
            int transportId = 0;
            transportId = Convert.ToInt32(ddlTransport.SelectedValue, CultureInfo.CurrentCulture);
            ListBillNos(transportId);
            //   btnViewBill.Enabled = true;
            //   btnApproveBill.Enabled = true;
            //  btnDeleteBill.Enabled = true;
        }
        else
        {
            ddlBillNos.DataSource = new object[] { };
            ddlBillNos.DataBind();
            btnViewBill.Enabled = false;
            //   btnApproveBill.Enabled = false;
            btnDeleteBill.Enabled = false;
        }

    }
    protected void btnSearchChallan_Click(object sender, EventArgs e)
    {
        CallListBillDetails();

    }

    private void CallListBillDetails()
    {
        Challan ch = new Challan();
        ch.TransComp = ddlTransportComp.SelectedItem.Text;
        ch.ContComp = ddlContractorComp.SelectedItem.Text;
        ch.MaterialDetail = ddlMaterial.SelectedItem.Text;
        System.Data.DataTable dt = new System.Data.DataTable();
        string fromDate = "";
        string toDate = "";
        fromDate = Request.Form[txtFromDate.UniqueID];
        toDate = Request.Form[txtToDate.UniqueID];
        dt = ch.GetBillDetails(fromDate, toDate);
        if (dt.Rows.Count > 0)
        {
            grdBill.DataSource = dt.DefaultView;
            grdBill.DataBind();
            btnGenerateBill.Enabled = true;
            btncreateBill.Enabled = true;
        }
        else
        {
            grdBill.DataSource = new Object[] { };
            grdBill.DataBind();
            btnGenerateBill.Enabled = false;
            btncreateBill.Enabled = false;
        }

    }

    private void CallFillComboBoxes()
    {
        ListCompany(ddlContractorComp, BusinessClass.CompanyType.Contractor);
        ListCompany(ddlTransportComp, BusinessClass.CompanyType.Transport);
        ListMaterial();
    }

    private void ListBillNos(int transportId)
    {
        try
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt = DataAccessClass.GetBillNos(false, transportId);
            if (dt.Rows.Count > 0)
            {
                ddlBillNos.DataSource = dt.DefaultView;
                ddlBillNos.DataTextField = "BillDetail";
                ddlBillNos.DataValueField = "BillNo";
                ddlBillNos.DataBind();
                btnViewBill.Enabled = true;
                btnDeleteBill.Enabled = true;
            }
            else
            {
                ddlBillNos.Items.Clear();
                ddlBillNos.DataSource = new object[] { };
                ddlBillNos.DataBind();
                btnViewBill.Enabled = false;
                btnDeleteBill.Enabled = false;
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void ListCompany(DropDownList ddl, BusinessClass.CompanyType companyType)
    {
        try
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt = DataAccessClass.GetCompany(companyType);
            ddl.DataSource = dt.DefaultView;
            ddl.DataTextField = "CompanyName";
            ddl.DataValueField = "CompanyId";
            ddl.DataBind();
        }
        catch (Exception ex)
        {
        }
    }

    private void ListMaterial()
    {
        try
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt = DataAccessClass.GetMaterial();
            ddlMaterial.DataSource = dt.DefaultView;
            ddlMaterial.DataTextField = "Material";
            ddlMaterial.DataValueField = "MaterialId";
            ddlMaterial.DataBind();
        }
        catch (Exception ex)
        {
        }
    }


    private void CallGenerateBill()
    {
        string xmlString = "";
        decimal rate = 0;
        rate = Convert.ToDecimal(txtRate.Text.Trim());
        DataSet ds = new DataSet("DsChallan");
        System.Data.DataTable dtChallan = new System.Data.DataTable("DtChallan");
        DataColumn dc;
        dc = new DataColumn("ChallanId");
        dtChallan.Columns.Add(dc);
        DataRow dr;
        System.Web.UI.WebControls.CheckBox chk;
        HiddenField hdnChId;
        foreach (GridViewRow gvr in grdBill.Rows)
        {
            chk = ((System.Web.UI.WebControls.CheckBox)gvr.FindControl("chkSelect"));
            hdnChId = ((HiddenField)gvr.FindControl("hdnChallanId"));
            if (chk.Checked)
            {
                dr = dtChallan.NewRow();
                dr["ChallanId"] = hdnChId.Value;
                dtChallan.Rows.Add(dr);
            }
        }
        ds.Tables.Add(dtChallan);
        xmlString = System.Xml.XmlConvert.DecodeName(ds.GetXml());
        DataSet ds1 = new DataSet();
        ds1 = DataAccessClass.GenerateBill(xmlString, 0, rate, txtToDate.Text);
        // CreateWordFile(ds1);
        CreateBill(ds1);
    }

    private void CreateBill(DataSet ds1)
    {
        Session["dsBillDetails"] = ds1;
        this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Window", "window.open('BillDetails.aspx','Bill','toolbar=0,resizable=0,scrollbars=1');", true);
    }



    protected void btnViewBill_Click(object sender, EventArgs e)
    {
        int billNo = 0;
        if (ddlBillNos.Items.Count > 0)
        {
            billNo = Convert.ToInt32(ddlBillNos.SelectedValue);
            DataSet ds1 = new DataSet();
            ds1 = DataAccessClass.GenerateBill(null, billNo);
            // CreateWordFile(ds1);
            CreateBill(ds1);
        }
    }
    #endregion


    protected void grdCOmpany_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HiddenField hdn;
            AjaxControlToolkit.ConfirmButtonExtender btnExt;
            btnExt = (AjaxControlToolkit.ConfirmButtonExtender)e.Row.FindControl("cnfrm");
            hdn = (HiddenField)e.Row.FindControl("IsDelete");
            LinkButton lbn;
            lbn = (LinkButton)e.Row.FindControl("lbnDelete");
            LinkButton lbn1;
            lbn1 = (LinkButton)e.Row.FindControl("lbnCompanyType");
            if (hdn.Value == "1")
            {
                lbn.Enabled = false;
                btnExt.ConfirmText = "You can not delete this record as it is included in the bill";
                lbn1.Enabled = false;

            }
            else
            {
                lbn.Enabled = true;
                lbn1.Enabled = true;
            }
        }
    }

    protected void grdChallan_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HiddenField hdn;
            AjaxControlToolkit.ConfirmButtonExtender btnExt;
            btnExt = (AjaxControlToolkit.ConfirmButtonExtender)e.Row.FindControl("cnfrm");
            hdn = (HiddenField)e.Row.FindControl("IsDelete");
            LinkButton lbn;
            lbn = (LinkButton)e.Row.FindControl("lbnDelete");
            LinkButton lbn1;
            lbn1 = (LinkButton)e.Row.FindControl("lbnChallanNo");
            if (hdn.Value == "1")
            {
                lbn.Enabled = false;
                btnExt.ConfirmText = "You can not delete this record as it is included in the bill";
                lbn1.Enabled = false;

            }
            else
            {
                lbn.Enabled = true;
                lbn1.Enabled = true;
            }
        }
    }
}